import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';

class HttpDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return  Scaffold(
        appBar: AppBar(
          title:Text('HttpDemo'),
          elevation: 0.0,
        ),
        body:HttpHome()
      );
  }
}

class HttpHome extends StatefulWidget {
  @override
  _HttpHomeState createState() => _HttpHomeState();
}

class _HttpHomeState extends State<HttpHome> {

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //featchPosts().then((value) => print(value));
  }

 Future<List<Post>> featchPosts() async{
     final response = await http.get('http://3.0.169.87:8080/pxmart/app/system/commonProblem');
     print(response.statusCode);
     if (response.statusCode == 200) {
       final responseBody = json.decode(response.body);
       List<Post> posts = responseBody['data']
       .map<Post>((item) => Post.fromJosn(item)).toList();
       return posts;
     }else{
       throw Exception('faile');
     }
 }
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: featchPosts(),
      builder: (BuildContext context, AsyncSnapshot snapshot){
        print('${snapshot.data}');
        if(snapshot.connectionState == ConnectionState.waiting){
             return Center(
               child:Text('loading.....')
             );
        }

        return ListView(
          children: snapshot.data.map<Widget>((item){
           return ListTile(
              title: Text(item.problem),
              subtitle: Text(item.answer),
            );
          }).toList(),
        );

      },
      
    );
  }
}

class Post{
  final int id;
  final String problem;
  final String answer;
  Post(
    this.id,
    this.problem,
    this.answer
  );
  Post.fromJosn(Map json)
        : id = json['id'],
        problem = json['problem'],
        answer = json['answer'];
  // Map toJson() => {
  //   'id' : id,
  //   'problem' : problem,
  //   'answer' : answer
  // };
}